package com.msb.dongbao.portal.web.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.msb.dongbao.common.util.CheckUtils;
import com.msb.dongbao.portal.web.api.posttest.SignDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: may
 * @date: 2021年05月30日 19:33
 */
@RestController
@RequestMapping("/api-safe")
@Slf4j
public class ApiSafeController {

    @GetMapping("/hello")
    public String hello() {
        return "hello api safe";
    }

    /**
     * 参数防篡改测试
     *
     * @param appid
     * @param name
     * @param sign
     * @param timestamp
     * @param request
     * @return java.lang.String
     */
    @GetMapping("/get-test")
    public String getTest(String appid, String name, String sign, long timestamp, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //map.put("appid", appid);
        //map.put("name", name);
        //map.put("timestamp", timestamp);

        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            map.put(parameterName, parameterValue);
        }

        //有效期内访问接口
        /*long time = System.currentTimeMillis() - timestamp;
        if (time > 1000 * 60) {
            return "接口过期了";
        }*/

        String generatorSign = CheckUtils.generatorSign(map);
        if (generatorSign.equals(sign)) {
            return "校验通过";
        }
        return "校验不通过";
    }

    @PostMapping("/post-test")
    public String postTest(@RequestBody SignDTO signDTO) {
        JSONObject jsonObject = JSONUtil.parseObj(signDTO);
        log.info("controller参数：" + jsonObject.toString());
        /*//参数转map
        Map<String, Object> stringObjectMap = Convert.toMap(String.class, Object.class, jsonObject);
        //生成签名
        String serverSign = CheckUtils.generatorSign(stringObjectMap);
        //校验
        String clientSign = signDTO.getSign();
        if (serverSign.equals(clientSign)) {
            return "校验通过";
        }
        return "校验不通过";*/
        return "controller";
    }
}
